package com.hk.dyeyuesystem;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.hk.dyeyuesystem.db.DBOpenHelper;
import com.hk.dyeyuesystem.model.Book;
import com.hk.dyeyuesystem.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员管理图书相关操作
 */
public class BookAdminActivity extends AppCompatActivity implements View.OnClickListener {

//    意图指向
    private Intent intent;

    //  Initialize Toast
    private Toast toast;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    //    Initialize ListView
    private ListView bookListView;

    private Button bookAddBtn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_admin);

//        实例化
        dbOpenHelper = new DBOpenHelper(BookAdminActivity.this, "db_book_system", null, 1);
//        获取listView控制权
        bookListView = findViewById(R.id.query_book_list_view);

//        添加长按点击弹出选项框菜单
        bookListView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("选择操作！");
                menu.add(0,0,0,"更新图书");
                menu.add(0,1,0,"删除图书");
            }
        });

//        获取控制权
        bookAddBtn = findViewById(R.id.book_add_btn);
        bookAddBtn.setOnClickListener(this);
        /**
         * 查询出所有的图书信息并进行回显
         */
        findAllBook();


    }

    /**
     * 查询出所有的图书
     */
    private void findAllBook() {
//        获取打开的数据库
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor cursor = readableDatabase.query("BOOK", null, null, null, null, null, null);
//        存储获取到的数据
        List<Map<String, Object>> resultList = new ArrayList<>(50);

        while (cursor.moveToNext()) {
            Map<String, Object> map = new HashMap<>(8);
            String bookNumber = cursor.getString(1);
            String bookName = cursor.getString(2);
            String author = cursor.getString(3);
            String press = cursor.getString(4);
            Integer bookCount =null,bookRemaining = null;
            try {
                bookCount = Integer.valueOf(cursor.getString(5));
                bookRemaining = Integer.valueOf(cursor.getString(6));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                Log.e("BookAdminActivity.java","数据转化数字失败，请检查数据！");
            }
//                对数据进行封装
            map.put("bookNumber", bookNumber);
            map.put("bookName", bookName);
            map.put("author", author);
            map.put("press", press);
            map.put("bookCount", bookCount);
            map.put("bookRemaining", bookRemaining);
//                将封装的map集合存储到resulList集合中
            resultList.add(map);
        }
//        判断是否具有图书
        if (resultList == null || resultList.size() == 0) {
            toast = ToastUtil.toastHint(toast, BookAdminActivity.this, "暂时没有图书，请稍后查看！");
            return;
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(
                BookAdminActivity.this,
                resultList,
                R.layout.query_book,
                new String[]{
                        "bookNumber","bookName",
                        "author","press",
                        "bookCount","bookRemaining"
                },
                new int[]{
                        R.id.book_number,R.id.book_name,
                        R.id.book_author,R.id.book_press,
                        R.id.book_count,R.id.book_remaining
                }
        );
        bookListView.setAdapter(simpleAdapter);

    }


    /**
     * 给菜单项添加事件
     * @param item 菜单索引
     * @return
     */
    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
//        获取上下文
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
//        得到listView中选择的条目绑定的Id
        String id = String.valueOf(info.id);
//        得到列表子节点的视图
        View targetView = info.targetView;
        //                获取单列 某一元素的控制权
        TextView bookNumberText = targetView.findViewById(R.id.book_number);
//                获取元素内容
        String bookNumberToString = bookNumberText.getText().toString();
        Log.i("=====ListView列表绑定的ID==",id);
        Log.i("===== 对应的图书编号 ==",bookNumberToString);
        switch (item.getItemId()) {
            case 0:
                // TODO: 2021/12/19 完成事件操作(已完成)
//                更新事件的方法
                updateDiaLog(bookNumberToString);
                return true;
            case 1:
//                删除事件的方法
                deleteData(bookNumberToString);
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    /**
     * 通过图书编号删除此图书
     * @param bookNumberToString
     */
    private void deleteData(final String bookNumberToString) {
//        建立一个对话框
        //                添加一个弹出对话框
        AlertDialog alertDialog = new AlertDialog.Builder(BookAdminActivity.this).create();
//                设置提示
        alertDialog.setMessage("确定要删除该书籍吗？");
//                设置 确认按钮操作
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
                Cursor cursor = readableDatabase.query("BOOK", null, "BOOK_NUMBER = ?", new String[]{bookNumberToString}, null, null, null);
                if (cursor.moveToNext()) {
//                    提取出图书ID
                    String id = cursor.getString(0);
//                    通过图书编号判断该图书是否有部分已借出去，如果已借出，则不能删除
                    Cursor cursor1 = readableDatabase.query("ACCOUNT_BOOK_RELATION", null, "BID = ? AND STATUS = ? OR STATUS = ? OR STATUS = ?", new String[]{id,"0","1","3"}, null, null, null);
                    List<String> stringList = new ArrayList<>();
//                    判断是否有借阅记录
                    while (cursor1.moveToNext()) {
                        String s = cursor1.getString(3);
                        stringList.add(s);
                    }
                    if (stringList.size() > 0) {
                        for (String status : stringList) {
                            if ("0".equals(status) || "1".equals(status)) {
                                Log.i("BookAdminActivity--207行","删除失败，该图书已有部分被借阅！");
                                toast = ToastUtil.toastHint(toast,BookAdminActivity.this,"删除失败，该图书已有部分被借阅！");
                                return;
                            }
                        }
                    }
                    int delete = readableDatabase.delete("BOOK", "BOOK_NUMBER = ?", new String[]{bookNumberToString});
                    if (delete >= 1) {
                        Log.i("BookAdminActivity","删除成功,删除记录数："+delete);
                        toast = ToastUtil.toastHint(toast,BookAdminActivity.this,"删除成功！");
                        startActivityForResult(new Intent(BookAdminActivity.this,BookAdminActivity.class),RESULT_OK);
                        finish();
                        return;
                    }
                    toast = ToastUtil.toastHint(toast,BookAdminActivity.this,"删除失败,请刷新重试！");
                    return;
                }
                toast = ToastUtil.toastHint(toast,BookAdminActivity.this,"未查到此数据,请刷新重试！");
                return;
            }
        });
//        设置取消按钮操作
        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                toast = ToastUtil.toastHint(toast,BookAdminActivity.this,"本次操作已取消！");
                return;
            }
        });
//          显示对话框
        alertDialog.show();

    }

    /**
     * 通过BookNumber获取图书详情并更新图书
     * @param bookNumberToString 图书编号
     */
    private void updateDiaLog(String bookNumberToString) {
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor cursor = readableDatabase.query("BOOK", null, "BOOK_NUMBER = ?", new String[]{bookNumberToString}, null, null, null);
        Book book = null;
        while (cursor.moveToNext()) {
            String bookNumber = cursor.getString(1);
            String bookName = cursor.getString(2);
            String auhtor = cursor.getString(3);
            String press = cursor.getString(4);
            Integer bookNum = null,bookRemaining = null;
            try {
                bookNum = Integer.valueOf(cursor.getString(5));
                bookRemaining = Integer.valueOf(cursor.getString(6));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                Log.e("BookAdminActivity.java","数据转化数字失败，请检查数据！");
            }
//            通过构造函数封装数据
            book = new Book(bookNumber,bookName,auhtor,press,bookNum,bookRemaining);
        }
        if (book == null) {
            toast = ToastUtil.toastHint(toast,BookAdminActivity.this,"未查到此数据,请刷新重试！");
            return;
        }
        String toJSONString = JSON.toJSONString(book);
//        存储集合进行传递
        Bundle bundle = new Bundle();
        bundle.putString("book",toJSONString);
        intent = new Intent(BookAdminActivity.this,BookUpdateActivity.class);
//         指向更新页面
        intent.putExtras(bundle);
        startActivity(intent);
//        清除该界面
        finish();

    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

    /**
     * 点击事件触发
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.book_add_btn:
                intent = new Intent(BookAdminActivity.this,BookAddActivity.class);
//                指向新增页面
                startActivity(intent);
                finish();
                break;
        }

    }


}